<template>
  <div>
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      :visible.sync="visible"
      width="600px"
    >
      <el-form
        :model="studentForm"
        :rules="studentFormRules"
        ref="studentForm"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="年级：" prop="grade">
              <nice-select
                v-model="studentForm.grade"
                placeholder="请选择年级"
                clearable
                :options="selectEnums.grade"
                labelkey="name"
                valuekey="id"
                @change="changeGrade"
              ></nice-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班级：" prop="schoolClassId">
              <nice-select
                v-model="studentForm.schoolClassId"
                placeholder="请选择班级"
                clearable
                :options="classList"
              ></nice-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名：" prop="realName">
              <el-input
                v-model="studentForm.realName"
                placeholder="请输入姓名"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别：" prop="sex">
              <el-select v-model="studentForm.sex" placeholder="请选择性别">
                <el-option label="男" :value="0"></el-option>
                <el-option label="女" :value="1"></el-option>
                <el-option label="未知" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="账号：" prop="username">
              <el-input
                v-model="studentForm.username"
                placeholder="请输入账号"
                clearable
                :disabled="title === '编辑学生'"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人：" prop="contractUserName">
              <el-input
                v-model="studentForm.contractUserName"
                placeholder="请输入联系人"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系方式：" prop="mobile">
              <el-input
                v-model="studentForm.mobile"
                placeholder="请输入联系方式"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入学年份：" prop="startYear">
              <el-input
                v-model="studentForm.startYear"
                placeholder="例:2024"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false" size="small">取消</el-button>
        <el-button
          type="primary"
          @click="dataFormSubmit"
          size="small"
          v-preventReClick
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { cascadeQuery, tableUpdate } from "@/api/api.js";
import { addSchoolStudent } from "@/api/user.js";

import { adminschoolstudentsave } from "@/api/lcmapi.js";
export default {
  data() {
    const validateMobile = (rule, value, callback) => {
      if (!this.$valid.isMobile(value) && value) {
        callback(new Error("手机号格式错误"));
      } else {
        callback();
      }
    };
    return {
      visible: false,
      studentForm: {
        realName: "", // 姓名
        sex: "", // 性别
        startYear: "", // 地址
        username: "", // 账号
        mobile: "", // 联系方式
        schoolClassId: "", // 班级
        grade: "", // 年级
        contractUserName: "" // 联系人
      },
      classList: [],
      studentFormRules: {
        grade: [{ required: true, message: "请选择年级", trigger: "change" }],
        schoolClassId: [
          { required: true, message: "请选择班级", trigger: "change" }
        ],
        realName: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        username: [
          { required: true, message: "账号不能为空", trigger: "blur" },
          {
            min: 1,
            max: 20,
            message: "长度在 1 到 20 个数字",
            trigger: "blur"
          }
        ],
        mobile: [{ validator: validateMobile, trigger: "blur" }]
      }
    };
  },
  props: {
    title: "",
    schoolId: "",
    selectEnums: {
      type: Object,
      default: function() {
        return {};
      }
    },
    gradeList: {
      type: Array,
      default: function() {
        return [];
      }
    }
  },
  methods: {
    init(row) {
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["studentForm"].resetFields();
        if (row) {
          this.studentForm = {
            ...this.studentForm,
            ...JSON.parse(JSON.stringify(row))
          };
          // this.$set(
          //   this.studentForm,
          //   "contractUserName",
          //   row.contact ? row.contact.split("-")[0] : ""
          // );
          // this.studentForm.grade = row.rel_class
          //   ? +row.rel_class.split("-")[0]
          //   : "";
          this.changeGrade(true);
        } else {
          this.studentForm = {
            realName: "", // 姓名
            sex: "", // 性别
            startYear: "", // 地址
            username: "", // 账号
            mobile: "", // 联系方式
            schoolClassId: "", // 班级
            grade: "", // 年级
            contractUserName: "" // 联系人
          };
        }
      });
    },
    async changeGrade(init = false) {
      // 手动切换年级，清空班级，
      if (!init) {
        this.studentForm.schoolClassId = "";
      }
      let res = await cascadeQuery({
        table_name: "nice_school_classes",
        condition: {
          school_id: this.schoolId,
          init_grade: this.studentForm.grade,
          class_type: "normal"
        }
      });
      if (res[0]) {
        return;
      }
      if (res[1] && res[1].code === 0) {
        this.classList = res[1].data.map(ele => {
          return {
            label: ele.class_name,
            value: ele.id
          };
        });
        if (!this.studentForm.schoolClassId) {
          this.studentForm.schoolClassId = "";
        }
      } else {
        this.$message.error(res[1].msg);
      }
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["studentForm"].validate(valid => {
        if (valid) {
          this.submit();
        }
      });
    },
    async submit() {
      let argObj = {
        ...this.studentForm,
        schoolId: this.schoolId,
        user_type: 2,
        realName: this.studentForm.realName,
        sex: this.studentForm.sex,
        mobile: this.studentForm.mobile,
        startYear: this.studentForm.startYear
      };
      if (!this.studentForm.mobile) {
        delete argObj.mobile;
      }
      let res = await adminschoolstudentsave(argObj);
      // this.title === "新增学生"
      //   ?
      //   : await tableUpdate([
      //       {
      //         table_name: "sys_user",
      //         update: [
      //           {
      //             user_type: 2,
      //             sys_user_nice_user_base: [
      //               { ...argObj, mobile: this.studentForm.mobile },
      //             ],
      //             school_class_student: [
      //               {
      //                 school_id: this.schoolId,
      //                 source: 224,
      //                 schoolClassId: this.studentForm.schoolClassId,
      //                 grade: this.studentForm.grade,
      //                 graduates: "",
      //               },
      //             ],
      //             student_contractUserName: [
      //               {
      //                 contractUserName: this.studentForm.contractUserName,
      //                 contractUserName_mobile: this.studentForm.mobile,
      //               },
      //             ],
      //           },
      //         ],
      //         where: [
      //           {
      //             user_id: this.studentForm.user_id,
      //           },
      //         ],
      //       },
      //     ]);
      if (res[0]) {
        return;
      }
      let data = res[1];
      if (data && data.code === 0) {
        this.$message({
          message: this.title === "新增学生" ? "新增学生成功" : "编辑学生成功",
          type: "success",
          duration: 1500,
          onClose: () => {
            this.visible = false;
            this.$emit("refreshDataList");
          }
        });
      } else {
        this.$message.error(data.msg);
      }
    }
  }
};
</script>
